<template>
  <Card>
    <Form ref="searchForm" :label-width="90" :model="searchForm" inline>
      <FormItem label="日期：" prop="date">
        <DatePicker
          v-model="searchForm.date"
          format="yyyy-MM"
          placeholder="选择时间"
          type="month"
          @on-change="searchForm.date=$event"
        ></DatePicker>
      </FormItem>
      <Form-item style="margin-left:-90px;">
        <Button icon="md-search" type="primary" @click="handleSearch">搜索</Button>
        <Button @click="handleReset">重置</Button>
      </Form-item>
    </Form>
    <Button
      :disabled="exportBtnDisable"
      icon="md-cloud-download"
      style="margin-bottom:15px"
      type="primary"
      @click="exportLeaderPay"
    >导出
    </Button>
    <Table
      :columns="column"
      :data="data"
      :loading="loading"
      :summary-method="handleSummary"
      border
      show-summary
      size="small">
    </Table>
  </Card>
</template>
<script>
import {leaderPayList} from '../../api/pay'
import {getReportColumn} from '../../api/newPay'

export default {
  data() {
    return {
      searchForm: {
        date: null
      },
      loading: false,
      data: [],
      modal: false,
      importLoading: false,
      exportBtnDisable: false,
      column: []
    }
  },
  mounted() {
  },
  methods: {
    getReportColumn() {
      getReportColumn('领导工资统计').then(res => {
        this.column = res.data
      })
    },
    //导出
    exportLeaderPay() {
      const date = this.searchForm.date
      if (date) {
        window.location.href = '/api/exportLeaderPay?date=' + date
      }
    },
    getList() {
      this.loading = true
      leaderPayList(this.searchForm).then(res => {
        this.loading = false
        if (res.data) {
          this.column = res.data.columns
          this.data = res.data.personnelData
        }
      })
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
    },
    handleSearch() {
      this.getList()
    },
    handleSummary({columns, data}) {
      const sums = {}
      columns.forEach((column, index) => {
        const key = column.key
        if (index === 0) {
          sums[key] = {
            key,
            value: '合计'
          }
          return
        }
        if (index === 1) {
          sums[key] = {
            key,
            value: '-'
          }
          return
        }
        const values = data.map(item => Number(item[key]))
        if (!values.every(value => isNaN(value))) {
          const v = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[key] = {
            key,
            value: v.toFixed(2)
          }
        } else {
          sums[key] = {
            key,
            value: 'N/A'
          }
        }
      })

      return sums
    }
  }
}
</script>
